library(mgcv); library(data.table); library(gratia); library(marginaleffects); library(ggplot2); library(dplyr); library(tidyr); library(zoo); library(slider); library(here)
#####test Paracou####
obs <- read.csv("G:/My Drive/cesab bioforest/Data/aggregated_data_v9.csv")
setDT(obs)
obs=obs[obs$Site=="Paracou"]
setnames(obs, "Plot", "subplot")
obs$plot=gsub("_.", "",obs$subplot )
obs <- obs[!Year%in%1984:1990]
obs <- dcast(
obs,
subplot + plot + Year ~ variable,
value.var = "value"
)
##### upload data
load("../clim_by_site.rda")
clim_all=rbindlist(lapply(clim_by_site[["Paracou"]], function(x) x$climate[[1]]),
idcol = "plot")
#"Paracou", "Mbaiki", "Corinto", "SUAS", "Lesong", "Ulu Muda", "Sungai Lalang", "Tene", "Jari"
baseline <- clim_all[year >= 1981 & year <= 2010]
clim_stats <- baseline[, .(
mean_tmax = mean(tmax),
sd_tmax = sd(tmax),
mean_vpd = mean(vpd),
sd_vpd = sd(vpd),
mean_srad = mean(srad),
sd_srad = sd(srad),
mean_def = mean(def),
sd_def = sd(def)
), by = month]
clim_all <- merge(clim_all, clim_stats, by = "month", all.x = TRUE)
clim_all[, `:=`(
z_tmax = (tmax - mean_tmax) / sd_tmax,
z_vpd = (vpd - mean_vpd) / sd_vpd,
z_srad = (srad - mean_srad) / sd_srad,
z_def = (def - mean_def) / sd_def
)]
#climate anomalies follow inventories. For Paracou, mean per year before 1996, two years after
clim_all[, year_bin :=
ifelse(year <= 1995,
year, # keep original year
1997 + ((year - 1996) %/% 2) * 2 # 2-year bins
)]
census_anom <- clim_all[,.(
mean_z_tmax = mean(z_tmax, na.rm = TRUE),
mean_z_vpd = mean(z_vpd, na.rm = TRUE),
mean_z_srad = mean(z_srad, na.rm = TRUE),
mean_z_def = mean(z_def, na.rm = TRUE)
),
by = .(plot, year_bin)]
#AGB values before 1991 are not consistent
census_anom=census_anom[year_bin>=1991]
merged <- merge(
obs,
census_anom,
by.x = c("Year","plot"), by.y=c("year_bin","plot")
)
control=c(1,6,11,13,14,15)
merged$Treatment <- ifelse(merged$plot %in% control, "control", "disturbed")
merged$Treatment <- factor(merged$Treatment)
merged$plot <- factor(merged$plot)
merged$subplot <- factor(merged$subplot)